package com.example.spring.ai.controller;

import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.ai.chat.model.ChatResponse;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.model.Media;
import org.springframework.ai.openai.OpenAiChatModel;
import org.springframework.ai.openai.OpenAiChatOptions;
import org.springframework.ai.openai.api.ResponseFormat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.util.MimeTypeUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import reactor.core.publisher.Flux;

@RestController
@RequestMapping("/ai/openAiChat")
public class OpenAiChatController {

    private final OpenAiChatModel model;

    @Autowired
    public OpenAiChatController(OpenAiChatModel model) {
        this.model = model;
    }

    @RequestMapping("/runtimeOptions")
    public ChatResponse runtimeOptions(@RequestParam(value = "message", defaultValue = "讲个笑话") String message) {
        return model.call(new Prompt(message, OpenAiChatOptions.builder().model("chatgpt-4o-latest").temperature(0.8).build()));
    }

    /**
     * 分析图片内容并生成OpenAI模型响应
     *
     * @param image   上传的图片文件，格式需符合OpenAI模型要求（如PNG/JPG）
     * @param message 与图片关联的文本消息，用于提供上下文或问题描述
     * @return 包含模型分析结果的响应对象，包含文本回复和元数据
     */
    @RequestMapping("/analyzeImage")
    public Flux<ChatResponse> analyzeImage(@RequestParam("image") MultipartFile image, @RequestParam("message") String message) {
        // 将上传文件转换为可处理的资源对象
        Resource resource = image.getResource();

        /* 构建包含多媒体内容的消息体：
         * - 设置MIME类型为image/png（实际应根据文件类型动态设置）
         * - 将资源对象封装为媒体内容
         * - 组合文本消息和图片内容
         */
        UserMessage userMessage = new UserMessage(message, new Media(MimeTypeUtils.IMAGE_PNG, resource));

        /* 调用AI模型处理请求：
         * - 使用chatgpt-4o-latest模型版本
         * - 设置temperature=0.8平衡创造性和确定性
         * - 封装完整的交互上下文到Prompt对象
         */
        return model.stream(new Prompt(userMessage, OpenAiChatOptions.builder()
                .model("Qwen/QVQ-72B-Preview")
                .temperature(0.8)
                .build()));
    }

    @RequestMapping("/formatResponse")
    public ChatResponse formatResponse(@RequestParam(value = "message", defaultValue = "讲个笑话") String message) {
        String jsonSchema = """
        {
            "type": "object",
            "properties": {
                "steps": {
                    "type": "array",
                    "items": {
                        "type": "object",
                        "properties": {
                            "explanation": { "type": "string" },
                            "output": { "type": "string" }
                        },
                        "required": ["explanation", "output"],
                        "additionalProperties": false
                    }
                },
                "final_answer": { "type": "string" }
            },
            "required": ["steps", "final_answer"],
            "additionalProperties": false
        }
        """;
        return model.call(new Prompt(message, OpenAiChatOptions.builder()
                .responseFormat(new ResponseFormat(ResponseFormat.Type.JSON_SCHEMA, jsonSchema))
                .temperature(0.8)
                .build()));
    }
}